package bupt.xixi.netty;

import bupt.xixi.RpcServer;
import bupt.xixi.codec.CommonDecoder;
import bupt.xixi.codec.CommonEncoder;
import bupt.xixi.entity.RequestHandler;
import bupt.xixi.enumeration.Codec;
import bupt.xixi.registry.IServiceRegistry;
import bupt.xixi.registry.impl.ZkServiceRegistry;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.Data;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

@Component
@Data
public class NettyServer implements RpcServer {

    private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);

    private String host;
    private IServiceRegistry register;
    private RequestHandler requestHandler;
    public static final int PORT = 9999;
    private final Integer READ_IDLE = 3 * Codec.IDLE;
    private final Integer WRITE_IDLE = 0;
    private final Integer READ_WRITE_IDLE = 0;


    @SneakyThrows
    public NettyServer() {
        this.host = InetAddress.getLocalHost().getHostAddress();
        this.register = new ZkServiceRegistry();
        this.requestHandler = new RequestHandler();
        
    }

    @Override
    public void start() {
        logger.info("启动Netty服务中...");
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 256)
                    // .option(ChannelOption.SO_KEEPALIVE, true)
                    // .childOption(ChannelOption.TCP_NODELAY, true) //todo: 不明白这个配置
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // head -> out1 -> out2 -> in1 -> in2 -> tail
                            // Inbound的执行顺序为 read -> in1 -> in2 -> write
                            // 编码器： byteBuf ->
                            pipeline.addLast(new IdleStateHandler(READ_IDLE, WRITE_IDLE, READ_WRITE_IDLE));
                            pipeline.addLast(new CommonEncoder(Codec.SerializeType.KYRO));
                            // 解码器： RpcResponse -> byteBuf
                            pipeline.addLast(new CommonDecoder());
                            pipeline.addLast(new NettyServerHandler(register, requestHandler));
                        }
                    });
            ChannelFuture channelFuture = bootstrap.bind(NettyServer.PORT).sync();
            // NacosServiceProvider.shutdownHook(); // 注册钩子在结束前清除已在nacos注册的服务
            logger.info("NettyServer成功绑定{}端口", NettyServer.PORT);
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.error("启动服务器时发生错误：{}", e.getMessage());
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
